package com.fms.data.repository;

import com.fms.data.file.FileException;
import com.fms.data.file.IFlowSheetOperations;
import com.fms.model.IDecision;
import com.fms.model.ILogger;
import com.fms.model.domain.FlowSheet;
import com.fms.model.repository.IFlowSheetRepository;

public class FileFlowSheetRepository implements IFlowSheetRepository
{
	private IFlowSheetOperations ops;
	private ILogger	logger;
	private IDecision	overwriteDecision;

	public FileFlowSheetRepository( IFlowSheetOperations _ops, 
									ILogger _logger,
									IDecision _overwriteDescision)
	{
		this.ops = _ops;
		this.logger = _logger;
		this.overwriteDecision = _overwriteDescision;
	}

	
	public void save(FlowSheet sheet)
	{
		if(!ops.exists(sheet))
		{
			createFlowSheet(sheet);
		}
		else
		{
			//ops.save(sheet);
			//logger.log("Flow sheet was saved at: " + sheet.getFileName());
		}
		
	}
	
	
	public void saveAsNew(FlowSheet sheet)
	{
		if(ops.exists(sheet))
		{
			boolean continueWithSave = overwriteDecision.decide("File Exists", 
											"A file already exists at this location, would you like to continue?");
			if(continueWithSave)
			{
				ops.delete(sheet.getFileName());
				createFlowSheet(sheet);
			}
		}
		else
		{
			createFlowSheet(sheet);
		}
		
	}
	
	private void createFlowSheet(FlowSheet sheet)
	{
		try
		{
			ops.createTemplate(sheet);
			logger.log("Flow sheet was saved at: " + sheet.getFileName());
		} 
		catch (FileException e)
		{
			logger.log(e.getMessage());
		}
	}

}
